<template>
  <div class="like-button">
    <el-button
      :type="isLiked ? 'danger' : 'default'"
      :icon="isLiked ? 'Heart' : 'HeartFilled'"
      :loading="loading"
      @click="handleLikeClick"
      circle
    />
    <span class="like-count">{{ likeCount }}</span>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { likeApi } from '@/api/like'
import { ElMessage } from 'element-plus'
import { Heart, HeartFilled } from '@element-plus/icons-vue'

export default {
  name: 'LikeButton',
  components: {
    Heart,
    HeartFilled
  },
  props: {
    // 当前登录用户ID
    userId: {
      type: Number,
      required: true
    },
    // 类型：'post' 或 'comment'
    type: {
      type: String,
      required: true,
      validator: (value) => ['post', 'comment'].includes(value)
    },
    // 目标ID（帖子ID或评论ID）
    targetId: {
      type: Number,
      required: true
    }
  },
  setup(props) {
    const loading = ref(false)
    const isLiked = ref(false)
    const likeCount = ref(0)

    // 检查点赞状态
    const checkLikeStatus = async () => {
      try {
        const [statusResponse, countResponse] = await Promise.all([
          props.type === 'post'
            ? likeApi.isPostLiked(props.targetId, props.userId)
            : likeApi.isCommentLiked(props.targetId, props.userId),
          props.type === 'post'
            ? likeApi.getPostLikeCount(props.targetId)
            : likeApi.getCommentLikeCount(props.targetId)
        ])
        
        isLiked.value = statusResponse.data
        likeCount.value = countResponse.data
      } catch (error) {
        console.error('获取点赞状态失败:', error)
      }
    }

    // 处理点赞/取消点赞
    const handleLikeClick = async () => {
      if (loading.value) return
      loading.value = true

      try {
        if (isLiked.value) {
          await (props.type === 'post'
            ? likeApi.unlikePost(props.targetId, props.userId)
            : likeApi.unlikeComment(props.targetId, props.userId))
          likeCount.value--
          isLiked.value = false
          ElMessage.success('已取消点赞')
        } else {
          await (props.type === 'post'
            ? likeApi.likePost(props.targetId, props.userId)
            : likeApi.likeComment(props.targetId, props.userId))
          likeCount.value++
          isLiked.value = true
          ElMessage.success('点赞成功')
        }
      } catch (error) {
        ElMessage.error('操作失败，请重试')
        console.error('点赞操作失败:', error)
      } finally {
        loading.value = false
      }
    }

    onMounted(() => {
      checkLikeStatus()
    })

    return {
      loading,
      isLiked,
      likeCount,
      handleLikeClick
    }
  }
}
</script>

<style scoped>
.like-button {
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.like-count {
  font-size: 14px;
  color: #606266;
}
</style> 